package com.datastructure.test.stringtoint;

public class StringToInt {

    public static void main(String[] args) {
        StringToInt stringToInt = new StringToInt();
        String s = "+-5";
        int i = stringToInt.StrToInt(s);
        System.out.println(i);
    }

    public int StrToInt (String s) {
        // write code here
        StringBuilder stringBuilder = new StringBuilder();
        boolean isPositiveNumber = true;
        boolean lastNumberValue = false;
        boolean isConfirm = false;
        double pow = Math.pow(2, 31);
        double max = pow - 1;
        double min = -pow;
        for (int i = 0; i < s.length(); i++) {
            char charAt = s.charAt(i);
            if(lastNumberValue&&!Character.isDigit(charAt)){
                break;
            }
            if(charAt==' '){
                continue;
            }
            if(charAt=='+'){
                isConfirm=true;
            }
            if(!Character.isDigit(charAt)&&charAt!='-'&&charAt!='+'){
                break;
            }
            if (isConfirm&&charAt=='-'){
                break;
            }
            if(!lastNumberValue&&charAt=='-'){
                isConfirm=true;
                isPositiveNumber=false;
                continue;
            }
            if(i > 0 && !Character.isDigit(charAt)){
                break;
            }
            if(Character.isDigit(charAt)){
                lastNumberValue=true;
                isConfirm=true;
                stringBuilder.append(charAt);
            }
        }
        long result = 0;
        String s1 = stringBuilder.toString();
        int length = s1.length();
        if(length ==0){
            return 0;
        }
        for (int i = 0; i < length; i++) {
            result+=Math.pow(10,length-i-1)*(s1.charAt(i)-48);
        }
        if(!isPositiveNumber){
            result=(-result);
        }
        if(result> max){
            return (int)max;
        }
        if(result<min){
            return (int) min;
        }
        return (int)result;
    }
}
